<template>
	<view>
		<view class="signature-dialog" @click.stop @touchmove.prevent.stop>
			<view class="content-view">
				<view class="title-text">请写入签名</view>
				<view class="title-desc">用于生成电子合同，请认真签名。</view>
				<canvas canvas-id="signature-canvas" class="signature-canvas" @touchstart="touchstartEvent"
					@touchmove="touchmoveEvent"></canvas>
				<view class="button-view">
					<view class="button-item" @click="onClear">清除</view>
					<view class="button-item button-active" @click="exportFilePath">保存</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "SignatureDialog",
		data() {
			return {
				context: null,
				touch: 0, // Canvas 笔画数量
			};
		},
		beforeMount() {
			this.initCanvas()
		},
		methods: {
			/**
			 * Canvas开始滑动
			 */
			touchstartEvent(e) {
				this.touch += 1
				this.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y);
			},
			/**
			 * 滑动事件
			 */
			touchmoveEvent(e) {
				this.context.lineTo(e.changedTouches[0].x, e.changedTouches[0].y);
				this.context.stroke();
				this.context.draw(true);
				this.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y);
			},
			/**
			 * 清空Canvas
			 */
			onClear() {
				this.touch = 0
				this.context.draw();
			},
			/**
			 * Canvas导出图片
			 */
			exportFilePath() {
				this.context.draw(true, uni.canvasToTempFilePath({
					fileType: 'jpg',
					canvasId: 'signature-canvas',
					success: (res) => this.$emit('confirm', res.tempFilePath),
					fail: (err) => {
						console.log(err)
					}
				}))
			},
			/**
			 * 初始化Canvas
			 */
			initCanvas() {
				const context = uni.createCanvasContext('signature-canvas');
				context.draw()
				this.context = context
			}
		}
	}
</script>

<style scoped lang="scss">
	.signature-dialog {
		width: 100%;
		height: 100vh;
		background: rgba(6, 0, 0, 0.9);
		position: fixed;
		top: 0;
		left: 0;
		z-index: 21;
		@extend .column;
		justify-content: flex-start;
		padding-top: 158upx;

		.content-view {
			width: 649rpx;
			padding: 29upx;
			background: #FFFFFF;
			border-radius: 14rpx;
			padding-top: 40upx;

			.title-text {
				text-align: center;
				font-size: 29rpx;
				font-weight: 500;
				color: #2C1101;
			}

			.title-desc {
				text-align: center;
				font-size: 25rpx;
				font-weight: 500;
				color: #FF2615;
				margin-top: 18upx;
			}

			.signature-canvas {
				width: 100%;
				height: 326upx;
				background: #F7F2EE;
				border-radius: 14rpx;
				margin-top: 33upx;
			}

			.button-view {
				width: 100%;
				margin-top: 33upx;
				@extend .row-between;

				.button-item {
					width: calc(100% / 2 - 9upx);
					height: 91rpx;
					border-radius: 45rpx;
					border: 1rpx solid #FF2615;
					@extend .column;
					font-size: 29rpx;
					font-family: PingFangSC, PingFang SC;
					font-weight: 500;
					color: #FF2615;
				}

				.button-active {
					background: linear-gradient(180deg, #FF7065 0%, #FF2615 100%);
					color: white;
				}
			}
		}
	}
</style>